﻿namespace MvcXRepair.Controllers
{
    using System;
    using System.Text.RegularExpressions;
    using System.Web.Mvc;
    using System.Web.Security;
    using Microsoft.Web.WebPages.OAuth;
    using MvcXRepair.Models;
    using MvcXRepair.ViewModel;
    using MvcXRepairCustomer.CacheData;
    using MvcXRepairCustomer.Interfaces;
    using MvcXRepairCustomer.Services;
    using WebMatrix.WebData;
    using XRepair.Models;

    [Authorize]
    public class UserController : BaseController
    {
        IUserService _userService;
        IOrderService _orderService;

        public UserController()
        {
            _userService = new UserService();
            _orderService = new OrderService();
        }

        [AllowAnonymous]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;

            if ((_userSession != null && !_userSession.IsAuthenticated) || _userSession == null)
            {
                _formAuthentication.Signout();
                return View(new LoginViewModel());
            }

            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        [AllowAnonymous]
        //[ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if ((_userSession != null && !_userSession.IsAuthenticated) || _userSession == null)
            {
                if (ModelState.IsValid)
                {
                    User userInfo = _userService.GetUserInfoByCredentials(model);

                    if (userInfo != null)
                    {
                        this.UpdateCurrentSession(userInfo);
                        _formAuthentication.Signin(userInfo.Username, false);

                        return RedirectToAction("Index", "Home");
                    }
                }
            }

            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        [HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            _formAuthentication.Signout();

            return RedirectToAction("Login");
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        //[ValidateAntiForgeryToken]
        public ActionResult Register(AccountRegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User();
                user.Username = model.UserName;
                user.Password = model.Password;
                user.EmailAddress = model.EmailAddress;

                bool userAdded = _userService.AddNewUser(user);

                if (userAdded)
                {
                    var pendingOrder = Cache.WithdrawPendingOrder(Session.SessionID) as OrderViewModel;

                    if (pendingOrder != null)
                    {
                        _orderService.AddPendingOrder(model.UserName, pendingOrder);
                    }

                    return View("RegistrationSucceeded");
                }

                return RedirectToAction("irrelevant-access", "Error");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [AllowAnonymous]
        public string CheckRegistrationEmailExisting(string email)
        {
            return _userService.IsEmailOccupied(email) ? "true" : "false";
        }

        [AllowAnonymous]
        public string CheckRegistrationUsernameExisting(string username)
        {
            return _userService.IsUsernameOccupied(username) ? "true" : "false";
        }

        public string CheckChangePassword(string currentPassword)
        {
            return currentPassword == _userSession.Password ? "true" : "false";
        }

        [AllowAnonymous]
        public ActionResult Activate(string id)
        {
            bool activated = _userService.ActivateUserAccount(id);

            if (activated)
            {
                return View("ActivationSucceeded");
            }

            return RedirectToAction("irrelevant-access", "Error");
        }

        [HttpGet]
        public ActionResult ChangePassword()
        {
            var model = new ChangePasswordViewModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (ModelState.IsValid && model.CurrentPassword == _userSession.Password)
            {
                var isUpdated = _userService.ChangeUserPasswordByEmailAddress(_userSession.Email, model.NewPassword);

                if (isUpdated)
                {
                    ViewBag.Succeeded = isUpdated;
                    return View();
                }
            }

            return View();
        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult ResetPassword()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult ResetPassword(string email)
        {
            if (!string.IsNullOrEmpty(email))
            {
                bool isEmail = Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z");

                bool isUpdated = false;

                if (isEmail)
                {
                    isUpdated = _userService.UpdateUserPasswordByEmailAddress(email);
                }

                ViewBag.Succeed = isUpdated;
            }

            return View();
        }

        private void UpdateCurrentSession(User user)
        {
            _userSession.Password = user.Password;
            _userSession.RoleID = user.RoleID;
            _userSession.SessionDateTime = DateTime.Now;
            _userSession.UserID = user.ID;
            _userSession.Username = user.Username;
            _userSession.Email = user.EmailAddress;
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
